//
//  WNReadVC+Delegate.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/17.
//

import UIKit

extension WNReadVC: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
    /// 切换结果
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        guard !showSetting && !showTopBom else { return }
        isTransition = false
        updateRead((pageViewController.viewControllers?.first as? WNCurrentReadVC)?.recordModel)
    }
    
    /// 准备切换
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        guard !showSetting && !showTopBom else { return }
        isTransition = true
    }
    
    /// 获取上一页
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard !showSetting && !showTopBom else { return nil }
        tempNumber -= 1
        if pageViewController.transitionStyle == .pageCurl {
            var recModel = (viewController as? WNCurrentReadVC)?.recordModel
            if recModel == nil {
                recModel = (viewController as? WNCurrentReadBackVC)?.recordModel
            }
            return abs(tempNumber) % 2 == 0 ? getCurrentReadBackVC(getBeforeRead(recModel)) : getReadVC(recModel)
        }else {
            return getReadVC(getBeforeRead((viewController as? WNCurrentReadVC)?.recordModel))
        }
    }
    
    /// 获取下一页
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard !showSetting && !showTopBom else { return nil }
        tempNumber += 1
        if pageViewController.transitionStyle == .pageCurl {
            var recModel = (viewController as? WNCurrentReadVC)?.recordModel
            if recModel == nil {
                recModel = (viewController as? WNCurrentReadBackVC)?.recordModel
            }
            return abs(tempNumber) % 2 == 0 ? getCurrentReadBackVC(recModel) : getReadVC(getAfterRead(recModel))
        }else {
            let recModel = (viewController as? WNCurrentReadVC)?.recordModel
            return getReadVC(getAfterRead(recModel))
        }
    }
}

extension WNReadVC: SNCoverVCDelegate {
    /// 切换结果
    func coverController(_ coverController: SNCoverVC, currentController: UIViewController?, finish isFinish: Bool) {
        guard !showSetting && !showTopBom else { return }
        updateRead((currentController as? WNCurrentReadVC)?.recordModel)
    }
    
    /// 获取上一个控制器
    func coverController(_ coverVC: SNCoverVC, getAboveControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        guard !showSetting && !showTopBom else { return nil }
        return getReadVC(getBeforeRead(recordModel))
    }
    
    /// 获取下一个控制器
    func coverController(_ coverVC: SNCoverVC, getBelowControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        guard !showSetting && !showTopBom else { return nil }
        return getReadVC(getAfterRead(recordModel))
    }
}

extension WNReadVC {
    
    /// 书详情
    func getBookRequest() {
        provider_book.rx.request(.bookDetail(bookDetailModel?.bookId ?? ""))
            .asObservable().mapModel(BaseModel<BookDetailModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let m = model.data {
                    self?.bookDetailModel = m
                    self?.getChapterListRequest()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 章节列表
    func getChapterListRequest(_ isFirst: Bool = false) {
        provider_book.rx.request(.chapterList(bookDetailModel?.bookId ?? ""))
            .asObservable().mapModel(BaseModel<ChapterListModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else { return }
                if let arr = model.data?.list, arr.count > 0 {
                    self?.bookDetailModel?.freepage = model.data?.bookDetial?.freepage ?? 0
                    self?.chapterArr = arr
                    self?.chapterContentRequest(isFirst)
                    if isFirst {
                        self?.getRechargeList()
                        self?.getLikeRequest()
                        self?.getTaskRequest()
                        self?.getLimitedRequest()
                    }
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 章节内容
    func chapterContentRequest(_ isFirst: Bool = false) {
        if isFirst {
            // TODO: - ⚠️：FB深度跳转 & 详情页章节跳转
            if !isBlank(jumpChapterId) {
                let chapter = chapterArr.first(where: {$0.chapterId.stringValue == jumpChapterId})
                if chapter?.status == 2 {
                    saveAutoOpen(true)
                    getLockedChapterContent(NSNumber(value: wn_toInt(jumpChapterId)), chapter)
                }
                if bookDetailModel?.durChapterId == 0 {
                    if chapter?.status == 2 {
                        jumpChapterId = chapterArr.first?.chapterId.stringValue ?? "0"
                    }
                }else {
                    if chapter?.status == 2 {
                        jumpChapterId = "\(bookDetailModel?.durChapterId ?? 0)"
                    }
                }
                bookDetailModel?.durChapterId = wn_toInt(jumpChapterId)
                bookDetailModel?.durChapterName = chapterArr.first(where: {$0.chapterId.stringValue == jumpChapterId })?.chapterName
                selChapterId = NSNumber(value: bookDetailModel?.durChapterId ?? 0)
            }else {
                if bookDetailModel?.durChapterId == 0 {
                    bookDetailModel?.durChapterId = chapterArr[0].chapterId.intValue
                    bookDetailModel?.durChapterName = chapterArr[0].chapterName
                }
                selChapterId = NSNumber(value: bookDetailModel?.durChapterId ?? 0)
            }
        }
        if SNKeyedArchiver.isExist(bookDetailModel?.bookId ?? "", selChapterId.stringValue) {
            let cdModel = SNKeyedArchiver.unarchiver(bookDetailModel?.bookId ?? "", selChapterId.stringValue) as? ChapterDetailModel
            handleChapterContent(cdModel)
        }else {
            WNHUD.wn_showLoading()
            provider_book.rx.request(.chapterContent((bookDetailModel?.bookId ?? ""), selChapterId.intValue))
                .asObservable().mapModel(BaseModel<ChapterDetailModel>.self)
                .subscribe(onNext: { [weak self] (model) in
                    guard model.code == 0 else {
                        self?.wn_toast(model.msg ?? "")
                        return
                    }
                    WNHUD.wn_hide()
                    if let data = model.data {
                        self?.handleChapterContent(data, false)
                    }
                }, onError: { [weak self] (error) in
                    self?.wn_toast("Check the network connection")
                }).disposed(by: rx.disposeBag)
        }
    }
    
    /// 收藏
    func collectRequest(_ isExit: Bool = false) {
        if animationView.isAnimationPlaying {
            return
        }
        let colType = (bookDetailModel?.favorite ?? true) ? 2 : 1
        provider_book.rx.request(.collect(colType, bookDetailModel?.bookId ?? ""))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if model.data != nil {
                    if isExit {
                        self?.bookDetailModel?.favorite = (colType == 1 ? true : false)
                        NotificationCenter.default.post(name: WNNotiName.collectNoti, object: self, userInfo: ["favorite": colType == 1 ? true : false, "bookId": self?.bookDetailModel?.bookId ?? ""])
                        self?.stopReadTimer()
                    }else {
                        self?.wn_toast((self?.bookDetailModel?.favorite ?? true) ? "You have removed this book from your Library" : "You have added this book to your Library")
                        self?.bookDetailModel?.favorite = (colType == 1 ? true : false)
                        NotificationCenter.default.post(name: WNNotiName.collectNoti, object: self, userInfo: ["favorite": colType == 1 ? true : false, "bookId": self?.bookDetailModel?.bookId ?? ""])
                    }
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 购买章节
    func buyChapter(_ bookId: String, _ chapterId: NSNumber, _ gold: Int, _ isAuto: Bool = false) {
        if chapterId == -1 {
            WNBuriedManager.shared.buyBook(bookId)
        }else {
            WNBuriedManager.shared.buyChapter(chapterId.stringValue)
        }
        WNHUD.wn_showLoading()
        provider_pay.rx.request(.buyChapter(bookId, chapterId.intValue, gold))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] model in
                guard model.code == 0 else {
                    WNHUD.wn_show(model.msg ?? "")
                    if chapterId == -1 {
                        WNBuriedManager.shared.buyBookFailed(bookId)
                    }else {
                        WNBuriedManager.shared.buyChapterFailed(chapterId.stringValue)
                    }
                    return
                }
                WNHUD.wn_hide()
                if model.data != nil {
                    self?.getUserGold({ _ in})
                    if isAuto {
                        if chapterId.intValue != -1 {
                            self?.selChapterId = chapterId
                        }
                        self?.getChapterListRequest()
                    }else {
                        self?.readLockView.isHidden = true
                        self?.animationView.isHidden = false
                        self?.animationView.play { (finsihed) in
                            if finsihed {
                                self?.animationView.isHidden = true
                                if chapterId.intValue != -1 {
                                    self?.selChapterId = chapterId
                                }
                                self?.getChapterListRequest()
                            }
                        }
                    }
                }
            }, onError: { (error) in
                WNHUD.wn_show("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 获取解锁章节内容
    func getLockedChapterContent(_ chapterId: NSNumber, _ chapterModel: ChapterDetailModel?) {
        provider_book.rx.request(.chapterContent((bookDetailModel?.bookId ?? ""), chapterId.intValue))
            .asObservable().mapModel(BaseModel<ChapterDetailModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let data = model.data {
                    let m = data
                    m.price = chapterModel?.price ?? 0
                    m.status = chapterModel?.status ?? 2
                    m.chapterId = chapterModel?.chapterId ?? 0
                    m.chapterName = chapterModel?.chapterName ?? ""
                    m.updateFont(false)
                    if self!.showTopBom {
                        self?.hiddenView()
                    }
                    self?.readLockView.isHidden = false
                    self?.readLockView.chapterModel = m
                    self?.navView.titleName = m.chapterName
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 章节阅读
    func chapterReadRequest() {
        WNBuriedManager.shared.readChapterStart(bookDetailModel?.bookId ?? "", "\(recordModel?.chapterModel?.chapterId.intValue ?? 0)")
        provider_book.rx.request(.chapterRead(bookDetailModel?.bookId ?? "", recordModel?.chapterModel?.chapterId.intValue ?? 0, recordModel?.chapterModel?.chapterName ?? "", READ_RECORD_CURRENT_CHAPTER_LOCATION))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else { return }
                if model.data != nil {
                    NotificationCenter.default.post(name: WNNotiName.chapterReadNoti, object: self, userInfo: ["chapterId": self?.recordModel?.chapterModel?.chapterId.intValue ?? 0, "chapterName": self?.recordModel?.chapterModel?.chapterName ?? ""])
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 充值列表
    func getRechargeList() {
        provider_setting.rx.request(.rechargeList)
            .asObservable().mapModel(BaseModel<[RechargeDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let arr = model.data, arr.count > 5 {
                    self?.rechargeArr = Array(arr[2..<arr.count])
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 猜你喜欢
    func getLikeRequest() {
        provider_discover.rx.request(.guesslike(1))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let arr = model.data {
                    let fArr = arr.filter({$0.bookId != self?.bookDetailModel?.bookId ?? ""})
                    self?.recArr = fArr
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 获取阅读随机奖励任务
    func getTaskRequest() {
        provider_task.rx.request(.getTask)
            .asObservable().mapModel(BaseModel<[TaskModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                if let arr = model.data {
                    self?.activeTaskModel = arr.filter({$0.taskType == 3}).first
                    self?.startReadTimer()
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    /// 完成阅读随机奖励任务
    func taskRequest(_ taskId: Int, _ gold: Int) {
        provider_task.rx.request(.completeTask(taskId))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                self?.navView.rightBtn.layer.removeAllAnimations()
                self?.navView.ishiddRightBtn = true
                self?.wn_toast(gold > 0 ? "Get \(gold) coins" : (model.msg ?? ""))
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 获取限时充值奖励任务
    func getLimitedRequest() {
        provider_setting.rx.request(.rechargeLimited)
            .asObservable().mapModel(BaseModel<[RechargeDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if let arr = model.data {
                    self?.limitedArr = arr
                    self?.handleLimitedArr()
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 章节完读
    func chapterReadComplete(_ chapterId: Int = 0, _ chapterName: String = "") {
        provider_book.rx.request(.chapterReadComplete(bookDetailModel?.bookId ?? "", chapterId, chapterName))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else {
                    return
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
}
